/*
解决办法： 一步一步的来实现各个模块

1.先显示一个自定义的view,设置View的大小
2.设置背景图片
3.通过绘图来获得当前屏幕的截图
4.添加毛玻璃效果
5.自定义Button
6.在 layoutSubViews方法里 去修改 titleLabel和imageView的frame
7.添加一个测试按钮，看一下自定义的button效果怎么样
8.通过一个循环来实现，添加6个按钮。重点就是 按钮的布局
9.通过plist 实现数据展示
10.通过pop来实现动画
11. 添加按钮的点击动画
12.实现我们的页面跳转【可以把控制传值到视图里（实际开发过程中，经常用到的 顺传控制器），但是要注意 循环引用的问题】
*/

import UIKit
import pop

class YYPopView: UIView {

    var target: UIViewController?


    private lazy var composeButton :[UIButton] = [UIButton]()


    override init(frame: CGRect) {
        super.init(frame: frame)

        self.frame.size = CGSizeMake(kUIScreenWidth, kUIScreenHeight)

        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){

        backgroundColor = UIColor.lightGrayColor()

        addSubview(bgImageView)

        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)

        }
        addchildButtons()
    }


    //添加子按钮
    private func addchildButtons(){


        //布局行和列    在实际开发中不要写死了,  定义一个常量
        //列
        let maxClo = 3

        //按钮的宽和高
        let childButtonWidth: CGFloat = 80
        let childButtonHeight: CGFloat = 110

        //按钮间的间距
        let margin = (kUIScreenWidth - CGFloat(maxClo) * childButtonWidth ) / CGFloat(maxClo + 1)
        //读取 plist
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        let composeButtonInfos = NSArray(contentsOfFile: path)!

        for i in 0..<composeButtonInfos.count{

            let popButton = YYPopButton()

            popButton.addTarget(self, action: "showVC:", forControlEvents: UIControlEvents.TouchUpInside)

            //设置按钮的 frame
            popButton.frame.size = CGSizeMake(childButtonWidth, childButtonHeight)

            let col = i % maxClo
            let row = i / maxClo

            popButton.frame.origin.x = margin * CGFloat(col + 1) + childButtonWidth * CGFloat(col)

            popButton.frame.origin.y = CGFloat(row) * (childButtonWidth + margin) + kUIScreenHeight

            //拿到数据
            let dic = composeButtonInfos[i] as! [String : AnyObject]
            let title = dic["title"] as? String
            let icon = dic["icon"] as! String

            popButton.setTitle(title, forState: UIControlState.Normal)

            popButton.setImage(UIImage(named: icon), forState: UIControlState.Normal)

            addSubview(popButton)

            composeButton.append(popButton)
        }
    }

    func anim(button: UIButton,beginTime: Double, isUp:Bool){

         let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)

        if isUp{

            animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y  - 400))
        }else{

            animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y + 400))
        }
        //弹簧的速度
        animation.springSpeed = 10

        //弹簧的效果
        animation.springBounciness = 8
        //动画开始时间
        animation.beginTime = beginTime

        button.pop_addAnimation(animation, forKey: nil)
    }

    class func testShow(target: UIViewController!){


        YYPopView().show(target)
    }


    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)  {

            for(index, button) in composeButton.reverse().enumerate(){

                anim(button, beginTime: CACurrentMediaTime() + Double(index) * 0.04, isUp: false)
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
                self.removeFromSuperview()

        }
    }

    private func show(target: UIViewController){

        self.target = target

        self.target?.view.addSubview(self)

        for(index, button) in composeButton.enumerate(){

             anim(button, beginTime: CACurrentMediaTime() + Double(index) * 0.04, isUp: true)
        }

    }

    @objc private func showVC(button: YYPopButton){

//
//        UIView.animateWithDuration(0.25, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 10, options:UIViewAnimationOptions.AllowAnimatedContent , animations: { () -> Void in

        UIView.animateWithDuration(0.25, animations: { () -> Void in


            for btn in self.composeButton{

                btn.alpha = 0

                if btn == button{

                    button.transform = CGAffineTransformMakeTranslation(1.5, 1.5)

                }else{
                    btn.transform = CGAffineTransformMakeScale(0.2,0.2)
                }

            }
            }) { (_) -> Void in
                //动画完成从父视图移除
            self.removeFromSuperview()
                let publish = YYPublishController()

                let nav = UINavigationController(rootViewController: publish)

                self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                    //
                })
        }
    }

    lazy var bgImageView: UIImageView = {

        let img = UIImageView()

        img.image = UIImage.getScreenShot()

        let effect = UIBlurEffect(style: UIBlurEffectStyle.Light)

        let effectView = UIVisualEffectView(effect: effect)

        img.addSubview(effectView)

        effectView.snp_makeConstraints(closure: { (make) -> Void in
            make.edges.equalTo(img.snp_edges)

        })

        return img
    }()
 }
